<template>
    <div class="login">
    <el-tabs type="border-card">
        <el-tab-pane label="密码登录">
        <el-form ref="loginBodyData" :model="loginBodyData" :rules="loginRules" class="login-form">
            <h3 class="title">天天向上后台管理系统</h3>
            <el-form-item prop="username">
                <el-input
                        v-model="loginBodyData.username"
                        type="text"
                        auto-complete="off"
                        placeholder="账号"
                        prefix-icon="el-icon-user"
                >
                </el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input
                        v-model="loginBodyData.password"
                        type="password"
                        auto-complete="off"
                        placeholder="密码"
                        @keyup.enter.native="handleLogin"
                        prefix-icon="el-icon-lock"
                >
                </el-input>
            </el-form-item>

            <el-form-item style="width:100%;">
                <el-button
                        :loading="loading"
                        size="medium"
                        type="primary"
                        style="width:100%;"
                        @click.native.prevent="handleLogin"
                >
                    <span v-if="!loading">登 录</span>
                    <span v-else>登 录 中...</span>
                </el-button>
            </el-form-item>
            <el-form-item style="margin-bottom: 0;">
                <div class="other-login-box" style="cursor: pointer;">
                    <img @click="handleSocialLogin('gitee')" src="../assets/logo/gitee.png" title="使用码云登录">
                    <img @click="handleSocialLogin('github')" src="../assets/logo/github.png" title="使用github登录">
                    <img @click="handleSocialLogin('dingtalk')" src="../assets/logo/dingtalk.png" title="使用钉钉登录">
<!--                    <img @click="handleSocialLogin('qq')" src="../assets/logo/qq.png" title="使用qq登录">-->
<!--                    <img @click="handleSocialLogin('wechat')" src="../assets/logo/wechat.png" title="使用微信登录">-->
<!--                    <img @click="handleSocialLogin('weibo')" src="../assets/logo/weibo.png" title="使用微博登录">-->
                </div>
                <div id="login_container"></div>
            </el-form-item>
        </el-form>
        </el-tab-pane>
        <el-tab-pane label="免密登录">
            <el-form ref="smsLoginForm" :model="smsLoginForm" :rules="smsLoginRules" class="login-form">
                <el-form-item prop="phoneNumber">
                    <el-input style="width: 60%" v-model.number="smsLoginForm.phoneNumber" type="text" auto-complete="off" placeholder="手机号码">
                    </el-input>
                    <el-button class="login-code"
                               :loading="loading"
                               size="small"
                               type="primary"
                               style="width: 35%;"
                               :disabled="!smsLoginForm.show"
                               @click.native.prevent="sendValidCode"
                    >
                        获取验证码
                        <span v-show="!smsLoginForm.show" class="count">({{smsLoginForm.count}}s)</span>
                    </el-button>
                </el-form-item>
                <el-form-item prop="validCode">
                    <el-input v-model="smsLoginForm.validCode" type="text" auto-complete="off" placeholder="验证码">
                    </el-input>
                </el-form-item>
                <el-form-item style="width:100%;">
                    <el-button
                            :loading="loading"
                            size="medium"
                            type="primary"
                            style="width:100%;"
                            @click.native.prevent="handleSmsLogin"
                    >
                        <span v-if="!loading">登 录</span>
                        <span v-else>登 录 中...</span>
                    </el-button>
                </el-form-item>
            </el-form>
        </el-tab-pane>
    </el-tabs>
        <!--  底部  -->
        <div class="el-login-footer">
            <span>Copyright © 2021 ttxs.com All Rights Reserved.</span>
        </div>
    </div>
</template>
<script>
    import {login, sendValidCode, smsLogin, snsLogin} from '@/api/login'
    import {saveLoginInfo} from "@/utils/session_storage"
    export default {
        name: 'Login',
        data() {
            // 手机号验证
            const validatePhoneNumber = (rule, value, callback) => {
                if (value === "") {
                    callback(new Error("请输入手机号"));
                } else {
                    if (!/^1[3456789]\d{9}$/.test(value)) {
                        callback(new Error("请输入正确的手机号"));
                    } else {
                        callback();
                    }
                }
            }
            // 验证码验证
            const validateValidCode = (rule, value, callback) => {
                if (value === "") {
                    callback(new Error("请输入验证码"));
                } else {
                    if (!/^\d{4}$/.test(value)) {
                        callback(new Error("请输入正确的4位数字验证码"));
                    } else {
                        callback();
                    }
                }
            }
            return {
                loginBodyData: {
                    username: 'admin',
                    password: 'ttxs',
                },
                loginRules: {
                    username: [
                        { required: true, trigger: "blur", message: "请输入您的账号" }
                    ],
                    password: [
                        { required: true, trigger: "blur", message: "请输入您的密码" }
                    ],
                },
                loading: false,
                smsLoginForm: {
                    show: true, // 初始启用按钮
                    count: '', // 初始化次数
                    timer: null,
                    phoneNumber: '',
                    validCode: ''
                },
                smsLoginRules: {
                    phoneNumber: [
                        { required: true, trigger: "blur", message: "手机号码不能为空" },
                        { validator: validatePhoneNumber, trigger: "blur"}
                    ],
                    validCode: [
                        { required: true, trigger: "blur", message: "验证码不能为空" },
                        { validator: validateValidCode, trigger: "blur"}
                    ],
                },
            }
        },
        created() {
            // 请求第三方登录的授权码后回调到本组件，地址栏携带了code和state
            // 继续调用后端控制器，通过code向第三方网址获取access_token
            // 通过access_token获取用户信息
            let code = this.getUrlKey('code');
            let state = this.getUrlKey('state') || '';
            if(code) {
                var platformName = sessionStorage.getItem('snsLoginPlatformName');
                snsLogin({code, state, platformName}).then(res=>{
                    this.$message({message:'登录成功', type:'success'})
                    saveLoginInfo(res.data)
                    location.href = '/'
                }).catch((e)=>{
                    console.log(e);
                })
            }
        },
        methods: {
            handleLogin() {
                this.$refs.loginBodyData.validate(valid => {
                    if(valid) {
                        this.loading = true;
                        login(this.loginBodyData).then(res => {
                            this.$message({message:'登录成功', type:'success'})
                            saveLoginInfo(res.data)
                            this.$router.push('/')
                        }).catch(() => this.loading = false )
                    }
                });
            },
            handleSmsLogin() {
                this.loading = true;
                this.$refs.smsLoginForm.validate(valid => {
                    if(valid) {
                        let data = {
                            phoneNumber: this.smsLoginForm.phoneNumber,
                            validCode: this.smsLoginForm.validCode
                        }
                        smsLogin(data).then((res) => {
                            this.$message({message:'登录成功', type:'success'})
                            saveLoginInfo(res.data)
                            this.$router.push('/')
                            }).catch(() => { this.loading = false });
                    } else {
                        this.loading = false;
                    }
                });
            },
            sendValidCode() {
                this.$refs.smsLoginForm.validateField('phoneNumber', valid => {
                    if(!valid) {
                        const TIME_COUNT = 60 //更改倒计时时间,
                        if (!this.timer) {
                            this.smsLoginForm.count = TIME_COUNT;
                            this.smsLoginForm.show = false;
                            this.smsLoginForm.timer = setInterval(() => {
                                if (this.smsLoginForm.count > 0 && this.smsLoginForm.count <= TIME_COUNT) {
                                    this.smsLoginForm.count--;
                                } else {
                                    this.clearTimer()
                                }
                            }, 1000)
                        }
                        sendValidCode({phoneNumber: this.smsLoginForm.phoneNumber})
                            .then(res => {
                                if (res == 'success') {
                                    this.msgSuccess('发送验证码成功');
                                } else {
                                    this.clearTimer()
                                    this.msgError(res)
                                }
                            })
                    }
                });
            },
            handleSocialLogin(platformName) {
                sessionStorage.setItem('snsLoginPlatformName', platformName)
                this.$alert('正在进行' + platformName + '登录，请稍后...', '社交账号登录', {
                    confirmButtonText: '确定',
                    callback: action => {
                    }
                });
                location.href = 'http://localhost:7001/easybuy/sns/authorize/' + platformName
            }
        }
    }
</script>
<style>
    .login {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
        background-image: url("../assets/images/20110405197.jpg");
        background-size: cover;
    }
    .title {
        margin: 0px auto 30px auto;
        text-align: center;
        color: #707070;
    }

    .login-form {
        border-radius: 6px;
        background: #ffffff;
        width: 400px;
        padding: 25px 25px 5px 25px;
        .el-input {
            height: 38px;
            input {
                height: 38px;
            }
        }
        .input-icon {
            height: 39px;
            width: 14px;
            margin-left: 2px;
        }
    }
    .login-tip {
        font-size: 13px;
        text-align: center;
        color: #bfbfbf;
    }
    .login-code {
        width: 33%;
        height: 38px;
        float: right;
        img {
            cursor: pointer;
            vertical-align: middle;
        }
    }
    .el-login-footer {
        height: 40px;
        line-height: 40px;
        position: fixed;
        bottom: 0;
        width: 100%;
        text-align: center;
        color: #fff;
        font-family: Arial;
        font-size: 12px;
        letter-spacing: 1px;
    }
    .login-code-img {
        height: 38px;
    }
</style>
